layui.use(['element', 'laydate', 'form'], function () {
    var $ = layui.jquery;
    var form = layui.form;
    var laydate = layui.laydate;

    var build = $(".build-panel");

    //初始化laydate实例
    laydate.render({
        elem: '#laydate'
    });

    // 禁止选择网页文本
    $(document).on('selectstart', '.layui-card', function(){
        return false;
    });

    // 移动操作
    var downPosi, target = null, dragDom = null, timer = null;
    var areaPosi;
    $(document).on("mousedown", ".layui-form-item", function (e) {
        $this = $(this);
        timer = setTimeout(function () {
            downPosi = {'left': e.clientX - $this.offset().left,
                'top': e.clientY - $this.offset().top + 10};
            areaPosi = {'ltX': build.offset().left, 'ltY': build.offset().top,
                'rbX': build.offset().left + build.width(),
                'rbY': build.offset().top + build.height()};
            target = $this;
        }, 200);
    });
    $(document).on("click", "#html-body .layui-form-item", function (e) {
        $this = $(this);
        var type = $this.attr("id").split("_",1)[0];
        var name = $this.find("input").attr("name");
        switch (type) {
            case "select": {
                $("#html-value").empty();
                $("#html-value").append("<div class=\"layui-form element-panel layui-form-pane\">\n" +
                    "                    <div class=\"layui-form-item\">\n" +
                    "                        <label class=\"layui-form-label\">标识</label>\n" +
                    "                        <div class=\"layui-input-block\">\n" +
                    "                            <input type=\"text\" name=\"title\" autocomplete=\"off\" value=\"" + name + "\" placeholder=\"请输入字段标识\" class=\"layui-input\">\n" +
                    "                        </div>\n" +
                    "                    </div>\n" +
                    "                    <div class=\"layui-form-item\">\n" +
                    "                        <label class=\"layui-form-label\">标题</label>\n" +
                    "                        <div class=\"layui-input-block\">\n" +
                    "                            <input type=\"text\" name=\"title\" autocomplete=\"off\" placeholder=\"请输入标题\" class=\"layui-input\">\n" +
                    "                        </div>\n" +
                    "                    </div>\n" +
                    "                    <div class=\"layui-form-item\">\n" +
                    "                        <label class=\"layui-form-label\">表单类型</label>\n" +
                    "                        <div class=\"layui-input-block\">\n" +
                    "                            <input type=\"text\" name=\"title\" readonly value=\"select\" autocomplete=\"off\" placeholder=\"请输入标题\" class=\"layui-input\">\n" +
                    "                        </div>\n" +
                    "                    </div>\n" +
                    "                    <div class=\"layui-form-item\">\n" +
                    "                        <label class=\"layui-form-label\">placeholder</label>\n" +
                    "                        <div class=\"layui-input-block\">\n" +
                    "                            <input type=\"text\" name=\"title\" autocomplete=\"off\" placeholder=\"请输入placeholder\" class=\"layui-input\">\n" +
                    "                        </div>\n" +
                    "                    </div>\n" +
                    "                </div>")
                break;
            }
            case "password": {

                break;
            }
            case "option": {

                break;
            }
            case "upload": {

                break;
            }
            case "date": {

                break;
            }
            case "checkbox": {

                break;
            }
            case "switch": {

                break;
            }
            case "radio": {

                break;
            }
            case "textarea": {

                break;
            }
            case "button": {

                break;
            }
            case undefined: {

            }
        }
    });
    $(document).on("mousemove", function (e) {
        if(dragDom == null && target != null){
            dragDom = $("<div class='layui-form timo-compile element-panel layui-form-pane'></div>");
            var rom = Math.floor(Math.random()*10000 + 1);
            switch (target.attr("id")) {
                case "select": {
                    dragDom.append("<div class=\"layui-form-item\" id='select_" + rom + "'>\n" +
                        "                        <label class=\"layui-form-label\">输入框</label>\n" +
                        "                        <div class=\"layui-input-inline\">\n" +
                        "                            <input type=\"text\" name=\"title\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"请输入标题\"\n" +
                        "                                   class=\"layui-input\">\n" +
                        "                        </div>\n" +
                        "                    </div>");
                    break;
                }
                case "password": {
                    dragDom.append("<div class=\"layui-form-item\" id='password_" + rom + "'>\n" +
                        "                        <label class=\"layui-form-label\" >密码框</label>\n" +
                        "                        <div class=\"layui-input-inline\">\n" +
                        "                            <input type=\"password\" name=\"password\" placeholder=\"请输入密码\" autocomplete=\"off\"\n" +
                        "                                   class=\"layui-input\">\n" +
                        "                        </div>\n" +
                        "                    </div>");
                    break;
                }
                case "option": {
                    dragDom.append("<div class=\"layui-form-item\" id='option_" + rom + "'>\n" +
                        "                        <label class=\"layui-form-label\">选择框</label>\n" +
                        "                        <div class=\"layui-input-inline\">\n" +
                        "                            <select name=\"interest\" lay-filter=\"aihao\">\n" +
                        "                                <option value=\"\"></option>\n" +
                        "                                <option value=\"0\">写作</option>\n" +
                        "                                <option value=\"1\">阅读</option>\n" +
                        "                                <option value=\"2\">游戏</option>\n" +
                        "                                <option value=\"3\">音乐</option>\n" +
                        "                                <option value=\"4\">旅行</option>\n" +
                        "                            </select>\n" +
                        "                        </div>\n" +
                        "                    </div>");
                    break;
                }
                case "upload": {
                    dragDom.append("<div class=\"layui-form-item\" id='upload_" + rom + "'>\n" +
                        "                        <label class=\"layui-form-label\">上传文件</label>\n" +
                        "                        <div class=\"layui-input-inline\">\n" +
                        "                            <button type=\"button\" class=\"layui-btn upload-image\" name=\"image[]\"\n" +
                        "                                    attr=\"up-url=@{/upload/image}\" up-field=\"path\">\n" +
                        "                                <i class=\"layui-icon\">&#xe67c;</i>上传文件\n" +
                        "                            </button>\n" +
                        "                        </div>\n" +
                        "                        <div class=\"upload-show\"></div>\n" +
                        "                    </div>");
                    break;
                }
                case "date": {
                    dragDom.append(" <div class=\"layui-form-item\" id='date_" + rom + "'>\n" +
                        "                        <label class=\"layui-form-label\">时间选择</label>\n" +
                        "                        <div class=\"layui-input-inline\">\n" +
                        "                            <input type=\"text\" class=\"layui-input\" id=\"laydate\" placeholder=\"yyyy-MM-dd\">\n" +
                        "                        </div>\n" +
                        "                    </div>");
                    break;
                }
                case "checkbox": {
                    dragDom.append("<div class=\"layui-form-item\" id='checkbox_" + rom + "'>\n" +
                        "                        <label class=\"layui-form-label\">复选框</label>\n" +
                        "                        <div class=\"layui-input-block\">\n" +
                        "                            <input type=\"checkbox\" name=\"like[write]\" title=\"写作\">\n" +
                        "                            <input type=\"checkbox\" name=\"like[read]\" title=\"阅读\" checked=\"\">\n" +
                        "                            <input type=\"checkbox\" name=\"like[game]\" title=\"游戏\">\n" +
                        "                        </div>\n" +
                        "                    </div>");
                    break;
                }
                case "switch": {
                    dragDom.append("<div class=\"layui-form-item\" id='switch_" + rom + "'>\n" +
                        "                        <label class=\"layui-form-label\">开关</label>\n" +
                        "                        <div class=\"layui-input-block\">\n" +
                        "                            <input type=\"checkbox\" name=\"close\" lay-skin=\"switch\" lay-text=\"ON|OFF\">\n" +
                        "                        </div>\n" +
                        "                    </div>");
                    break;
                }
                case "radio": {
                    dragDom.append("<div class=\"layui-form-item\" pane=\"\" id='radio_" + rom + "'>\n" +
                        "                        <label class=\"layui-form-label\">单选框</label>\n" +
                        "                        <div class=\"layui-input-block\">\n" +
                        "                            <input type=\"radio\" name=\"sex\" value=\"男\" title=\"男\" checked=\"\">\n" +
                        "                            <input type=\"radio\" name=\"sex\" value=\"女\" title=\"女\">\n" +
                        "                            <input type=\"radio\" name=\"sex\" value=\"禁\" title=\"禁用\" disabled=\"\">\n" +
                        "                        </div>\n" +
                        "                    </div>");
                    break;
                }
                case "textarea": {
                    dragDom.append("<div class=\"layui-form-item layui-form-text\" id='textarea_" + rom + "'>\n" +
                        "                        <label class=\"layui-form-label\">文本域</label>\n" +
                        "                        <div class=\"layui-input-block\">\n" +
                        "                            <textarea placeholder=\"请输入内容\" class=\"layui-textarea\"></textarea>\n" +
                        "                        </div>\n" +
                        "                    </div>");
                    break;
                }
                case "button": {
                    dragDom.append("<div class=\"layui-form-item\" id='button_" + rom + "'>\n" +
                        "                        <div class=\"layui-input-block\">\n" +
                        "                            <button class=\"layui-btn ajax-submit\"><i class=\"fa fa-check-circle\"></i> 保存</button>\n" +
                        "                            <button class=\"layui-btn btn-secondary close-popup\"><i class=\"fa fa-times-circle\"></i> 关闭\n" +
                        "                            </button>\n" +
                        "                        </div>\n" +
                        "                    </div>");
                    break;
                }
                default:{
                    dragDom.append(target.clone());
                    break;
                }
            }
            dragDom.addClass("drag-box");
            dragDom.css("width", target.width());
            $("body").append(dragDom);
            var buildItem = target.parent('.build-item');
            if(buildItem.length > 0){
                buildItem.remove();
            }
        }
        if(dragDom != null){
            dragDom.css("left", e.clientX - downPosi.left);
            dragDom.css("top", e.clientY - downPosi.top);
        }
        if(dragDom != null){
            if(e.clientX > areaPosi.ltX && e.clientY > areaPosi.ltY
                && e.clientX < areaPosi.rbX && e.clientY < areaPosi.rbY){
                build.addClass("active");
                buildItemPosi(e.clientY);
            }else{
                build.removeClass("active");
                shellItem.remove();
            }
        }
    });
    $(document).on("mouseup", function (e) {
        if(dragDom != null){
            if(build.hasClass("active")){
                buildAdd(dragDom);
            }
            dragDom.remove();
            dragDom = null;
            target = null;
            build.removeClass("active");
            shellItem.remove();
        }
        if(timer != null){
            clearTimeout(timer);
            timer = null;
        }
    });

    // 构建项位置
    var shellItem = $("<div id='shell-item'></div>");
    var buildItemPosi = function(clientY){
        build.children('.build-item').each(function(key, val){
            var $this = $(val);
            var ty = $this.offset().top;
            var by = $this.offset().top + $this.height();
            if(clientY > ty &&  clientY < by ){
                if(clientY < (ty + by) / 2){
                    $this.before(shellItem);
                }else{
                    $this.after(shellItem);
                }
            }
        });
        shellItem.css('height', dragDom.height());
        if($('#shell-item').length == 0){
            build.append(shellItem);
        }
    };

    // 加入构建面板
    var buildAdd = function(dragDom){
        var elem = dragDom.children(".layui-form-item").clone();
        elem.children('div').children('div').remove();
        elem.removeAttr('style');
        elem.removeClass('drag-box');
        var item = $("<div class='build-item'>" +
            "<div class='control'><a class='edit'>编辑HTML</a> | " +
            "<a class='remove'>删除</a></div>" +
            "</div>");
        shellItem.after(item.append(elem));

        form.render();
    };

    // 编辑构建项
    var buildItem, index;
    build.on('click', '.edit', function(){
        buildItem = $(this).parents('.build-item');
        var elem = buildItem.children('.layui-form-item').clone();
        elem.children('div').children('div').remove();
        elem.find('.layui-upload-file').remove();

        var box = $("<div class='build-edit-box'></div>");
        var edit = $("<textarea class='build-edit'></textarea>").text(elem.prop('outerHTML'));
        box.append(edit).append("<button class='build-edit-btn'>更新</button></div>");

        index = layer.open({
            title: '编辑HTML',
            type: 1,
            skin: 'build-item-edit', //样式类名
            shadeClose: true, //开启遮罩关闭
            area: ['500px', '360px'],
            content: box.prop('outerHTML')
        });
    });

    // 更新HTML
    $(document).on('click', '.build-edit-btn', function(){
        var val = $(this).parent().children('textarea').val();
        buildItem.children('.layui-form-item').remove();
        buildItem.append($(val));
        form.render();
        layer.close(index);
    });

    // 删除构建项
    build.on('click', '.remove', function(){
        $(this).parents('.build-item').remove();
    });

    // 生成代码
    $(document).on('click', '.build-generate', function(){
        var genHtml = '';
        build.find(".layui-form-item").each(function (key, val) {
            var item = $(val).clone();
            item.children('div').children('div').remove();
            item.find('.layui-upload-file').remove();
            genHtml += item.prop('outerHTML') + "\n";
        });
        var box = $("<div class='build-edit-box'></div>");
        var edit = $("<textarea class='build-edit'></textarea>").text(genHtml);
        box.append(edit);

        index = layer.open({
            title: '复制HTML代码',
            type: 1,
            skin: 'build-item-edit', //样式类名
            shadeClose: true, //开启遮罩关闭
            area: ['80%', '80%'],
            content: box.prop('outerHTML')
        });
        $('.build-edit').focus().select();
    });

});